#include "./header/tiny_client.h"

TC tiny_client::tiny_client(unsigned int IP_family)
{
	use_wsa();
	load_version();
	sockke = new SOCKET;
	addrke = new SOCKADDR_IN;
	addrke->sin_family = IP_family;
	*sockke = socket(IP_family, SOCK_STREAM, 0);
}

TC tiny_client::~tiny_client()
{
	WSACleanup();
	closesocket(*sockke);
	if (sockke != nullptr) delete sockke;
	if (addrke != nullptr) delete addrke;
}

bool TC tiny_client::Connect()
{
	return connect(*sockke, (sockaddr*)addrke, sizeof(SOCKADDR_IN)) == INVALID_SOCKET ? false : true;
}

void TC tiny_client::set_ip(std::string ip)
{
	addrke->sin_addr.S_un.S_addr = inet_addr(ip.c_str());
}

bool TC tiny_client::set_port(unsigned int port)
{
	if (port <= 2 * SHRT_MAX)
	{
		addrke->sin_port = htons(port);
		return true;
	}
	return false;
}

std::string TC tiny_client::get_user_IP()
{
	return inet_ntoa(addrke->sin_addr);
}

bool TC tiny_client::send_out(std::string content)
{
	return send(*sockke, content.c_str(), content.size() + 1, 0) == SOCKET_ERROR ? false : true;
}

std::string TC tiny_client::receive(unsigned int word_size)
{
	char* re = new char[word_size];
	memset(re, 0, word_size);

	if (recv(*sockke, re, word_size, 0) == SOCKET_ERROR)
	{
		delete[] re;
		return "";
	}
	std::string ans = re;
	delete[] re;
	return ans;
}